package com.xmut.mall.ware.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xmut.mall.ware.entity.WareOrderTaskDetailEntity;
import com.xmut.mall.ware.entity.WareSkuEntity;
import com.xmut.mall.ware.service.WareOrderTaskDetailService;
import com.xmut.mall.ware.service.WareSkuService;
import com.xmut.mall.ware.to.CreateOrderDto;
import com.xmut.mall.ware.vo.MemberCartEntityVo;
import com.xmut.mall.ware.vo.MemberReceiveAddressEntityVo;
import com.xmut.mall.ware.vo.remarkVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.ware.utils.PageUtils;
import com.xmut.mall.ware.utils.Query;

import com.xmut.mall.ware.dao.WareOrderTaskDao;
import com.xmut.mall.ware.entity.WareOrderTaskEntity;
import com.xmut.mall.ware.service.WareOrderTaskService;


@Service("wareOrderTaskService")
public class WareOrderTaskServiceImpl extends ServiceImpl<WareOrderTaskDao, WareOrderTaskEntity> implements WareOrderTaskService {

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareOrderTaskEntity> page = this.page(
                new Query<WareOrderTaskEntity>().getPage(params),
                new QueryWrapper<WareOrderTaskEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 创建工单
     *
     * @param param
     */
    @Override
    public void createWareOrderTask(Map<String, Object> param) {
        MemberReceiveAddressEntityVo address = MapUtil.get(param, "address", MemberReceiveAddressEntityVo.class);
        List<MemberCartEntityVo> memberCartEntityList = MapUtil.get(param, "memberCartEntityList", new TypeReference<List<MemberCartEntityVo>>() {
        });
        Map<Long, CreateOrderDto> createOrderIds = MapUtil.get(param, "createOrderIds", new TypeReference<Map<Long, CreateOrderDto>>() {
        });

        List<Long> storeIds = memberCartEntityList.stream().map(MemberCartEntityVo::getStoreId).distinct().collect(Collectors.toList());

        for (Long storeId : storeIds) {
            // 工单和订单一样 以店铺为单位 生成一个大工单 订单的具体商品变为工单的工单详情
            CreateOrderDto createOrderDto = createOrderIds.get(storeId);
            // 创建工单
            WareOrderTaskEntity wareOrderTask = new WareOrderTaskEntity();
            Long taskId = IdWorker.getId();// 工单Id;
            wareOrderTask.setId(taskId);
            wareOrderTask.setOrderSn(createOrderDto.getOrderSN());
            wareOrderTask.setConsignee(address.getName());
            wareOrderTask.setConsigneeTel(address.getMobile());
            wareOrderTask.setDeliveryAddress(address.getDetail());
            wareOrderTask.setTaskComment("锁库存");
            wareOrderTask.setTaskStatus(1);
            wareOrderTask.setCreateTime(new Date());
            List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntityList = new ArrayList<>();// 保存工单详情的List
            for (Long skuId : createOrderDto.getSkuIds()) {
                // 生成工单详情
                // 根据SkuId 从传入的购物车列表里面找出对应的项
                MemberCartEntityVo memberCartEntityVo = getMemberCart(memberCartEntityList,skuId);
                WareOrderTaskDetailEntity wareOrderTaskDetail = new WareOrderTaskDetailEntity();
                wareOrderTaskDetail.setSkuId(memberCartEntityVo.getSkuId());
                wareOrderTaskDetail.setSkuName(memberCartEntityVo.getSkuName());
                wareOrderTaskDetail.setSkuNum(Integer.parseInt(memberCartEntityVo.getProductCount().toString()));
                wareOrderTaskDetail.setTaskId(taskId);
                wareOrderTaskDetail.setLockStatus(1);
                wareOrderTaskDetail.setOrderSn(createOrderDto.getOrderSN());
                wareOrderTaskDetailEntityList.add(wareOrderTaskDetail);

                // 计算当前库存
                WareSkuEntity wareSkuEntity = wareSkuService.getOne(new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", memberCartEntityVo.getSkuId()));
                Integer nowStock =
                        wareSkuEntity.getStock() - Integer.parseInt(memberCartEntityVo.getProductCount().toString());
                //计算现在被锁定的库存
                Integer nowLock =
                        wareSkuEntity.getStockLocked() + Integer.parseInt(memberCartEntityVo.getProductCount().toString());
                // 给库存表扣库存
                wareSkuService.update(new UpdateWrapper<WareSkuEntity>()
                        .set("stock", nowStock)
                        .set("stock_locked", nowLock)
                        .eq("sku_id", memberCartEntityVo.getSkuId()));

            }

            // 最后一起保存
            wareOrderTaskDetailService.saveBatch(wareOrderTaskDetailEntityList);

            this.save(wareOrderTask);
        }

//        WareOrderTaskEntity wareOrderTask = new WareOrderTaskEntity();
//        Long taskId = IdWorker.getId();
//        wareOrderTask.setId(taskId);
//        wareOrderTask.setOrderSn(orderSN);
//        wareOrderTask.setConsignee(address.getName());
//        wareOrderTask.setConsigneeTel(address.getMobile());
//        wareOrderTask.setDeliveryAddress(address.getDetail());
//        wareOrderTask.setTaskComment("锁库存");
//        wareOrderTask.setTaskStatus(1);
//        wareOrderTask.setCreateTime(new Date());
//
//        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntityList = new ArrayList<>();
//        // 创建工单详情
//        for (MemberCartEntityVo entity : memberCartEntityList) {
//            WareOrderTaskDetailEntity wareOrderTaskDetail = new WareOrderTaskDetailEntity();
//            wareOrderTaskDetail.setSkuId(entity.getSkuId());
//            wareOrderTaskDetail.setSkuName(entity.getSkuName());
//            wareOrderTaskDetail.setSkuNum(Integer.parseInt(entity.getProductCount().toString()));
//            wareOrderTaskDetail.setTaskId(taskId);
//            wareOrderTaskDetail.setLockStatus(1);
//            wareOrderTaskDetail.setOrderSn(orderSN);
//            wareOrderTaskDetailEntityList.add(wareOrderTaskDetail);
//
//            // 计算当前库存
//            WareSkuEntity wareSkuEntity = wareSkuService.getOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", entity.getSkuId()));
//            Integer nowStock = wareSkuEntity.getStock() - Integer.parseInt(entity.getProductCount().toString());
//            //计算现在被锁定的库存
//            Integer nowLock = wareSkuEntity.getStockLocked() + Integer.parseInt(entity.getProductCount().toString());
//            // 给库存表扣库存
//            wareSkuService.update(new UpdateWrapper<WareSkuEntity>()
//                    .set("stock",nowStock)
//                    .set("stock_locked",nowLock)
//                    .eq("sku_id",entity.getSkuId()));
//        }
//
//        // 最后一起保存
//        wareOrderTaskDetailService.saveBatch(wareOrderTaskDetailEntityList);
//
//        this.save(wareOrderTask);


    }

    /**
     * 根据SkuId 从传入的购物车列表里面找出对应的项
     * @param memberCartEntityList
     * @param skuId
     * @return
     */
    private MemberCartEntityVo getMemberCart(List<MemberCartEntityVo> memberCartEntityList, Long skuId) {
        MemberCartEntityVo vo = new MemberCartEntityVo();
        for (MemberCartEntityVo memberCartEntityVo : memberCartEntityList) {
            if (memberCartEntityVo.getSkuId().equals(skuId)){
                return memberCartEntityVo;
            }
        }
        return vo;
    }


}